<template>
  <div class="content">
    <div class="wrap">
      <el-row :gutter="11">
        <el-col :span="8" v-for="(item, idx) of list" :key="item.id">
          <el-card style="margin-bottom: 11px; height: 317px">
            <div class="item">
              <img
                v-if="
                  item.serviceIcon == 'one' ||
                  item.serviceIcon == 'two' ||
                  item.serviceIcon == 'three'
                "
                :src="
                  require(`@/assets/imgs/middleWork/${item.serviceIcon}.png`)
                "
                class="img"
              />
              <img
                v-else
                :src="host + `/merchantApi/oss/view?id=${item.serviceIcon}`"
                class="img"
              />
              <div class="type" style="min-height: 48px">
                <div>{{ item.serviceName }}</div>
                <div class="meal" v-if="item.versionUp">
                  {{ item.mealName }}
                </div>
              </div>
              <div class="date" v-if="item.isBuy">
                <div v-if="item.isExpire">
                  <div>已过期 {{ item.expireDays }} 天</div>
                </div>
                <div v-else>{{ `有效日期至 ${item.expireDateStr}` }}</div>
              </div>
              <div class="date" v-else></div>
              <el-button
                type="primary"
                round
                class="btn"
                :class="
                  !item.isExpire && item.isBuy && item.versionUp
                    ? 'btn-small'
                    : ''
                "
                @click="
                  toPurchase(
                    idx,
                    item.id,
                    item.mealId,
                    !item.isExpire && item.isBuy ? 1 : 0
                  )
                "
                >{{
                  !item.isExpire && item.isBuy ? "续约" : "购买服务"
                }}</el-button
              >
              <!-- 升级套餐按钮 -->
              <el-button
                v-if="!item.isExpire && item.isBuy && item.versionUp"
                type="primary"
                round
                class="btn btn-small"
                @click="toPurchase(idx, item.id, item.mealId, 2)"
                >升级</el-button
              >
            </div>
            <div
              class="statusTip"
              v-if="!list[0].isExpire && !item.isExpire && item.isBuy"
            >
              正常使用中
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- <el-card style="margin: 0 20px">
            <div class="item">
                <img src="@/assets/imgs/middleWork/two.png" class="img">
                <div class="type">多商户管理系统</div>
                <div class="tag"></div>
                <div class="overdue">已过期</div>
                <el-button type="primary" round class="btn"></el-button>
            </div>
        </el-card>
        <el-card>
            <div class="item">
                <img src="@/assets/imgs/middleWork/three.png" class="img">
                <div class="type">账户系统</div>
                <div class="tag"></div>
                <div>正常使用中</div>
                <el-button type="primary" round class="btn">续约</el-button>
            </div>
        </el-card> -->
    </div>
    <el-card style="min-width: 1200px">
      <div class="wrap2">
        <div class="item2">
          <div>
            <span>企业服务余额</span>
            <span class="primary" v-if="authInfo.status == 'create'"
              >暂未开通</span
            >
            <span class="warn" v-if="authInfo.status == 'apply'"
              >申请开通中</span
            >
            <span class="error" v-if="authInfo.status == 'fail'">开通失败</span>
            <span class="number" v-if="authInfo.status == 'success'"
              >¥ {{ authAmount }}</span
            >
          </div>
          <div>
            <div v-if="authInfo.status == 'create'">
              <el-button
                type="primary"
                @click="createAuthAcc"
                style="width: 156px; border-radius: 16px"
                >申请开通</el-button
              >
            </div>
            <div v-if="authInfo.status == 'fail'">
              <el-button type="text" @click="toEditRegis">修改资料</el-button>
            </div>
            <div v-if="authInfo.status == 'success'">
              <el-button type="text" @click="openDia(2)">充值</el-button>
              <el-button type="text" class="look" @click="pathTo(1)"
                >查看余额明细</el-button
              >
            </div>
            <!-- <el-button type="text" class="look" @click="openDia1"
              >设置支付密码</el-button
            > -->
          </div>
        </div>
        <!-- <div class="item2 two">
          <div>
            <span>手续费余额</span>
            <span class="number">¥0.00</span>
          </div>
          <div>
            <el-button type="text" @click="openDia(1)" disabled>充值</el-button>
            <el-button type="text" class="look" @click="pathTo(0)" disabled
              >查看余额明细</el-button
            >
          </div>
        </div> -->
      </div>
    </el-card>

    <el-card style="min-width: 1200px; margin-top: 10px">
      <div class="wrap2">
        <div class="item2">
          <div>
            <span>鉴权剩余次数</span>
            <span class="number">{{ authCount }} 次</span>
          </div>
          <div>
            <div class="tip" v-if="authInfo.status != 'success'">
              请先开通企业服务余额，方可进行购买操作
            </div>
            <el-button
              v-else
              type="primary"
              style="width: 96px; border-radius: 16px"
              @click="openDia2"
              >购买</el-button
            >
          </div>
        </div>
      </div>
    </el-card>

    <!-- 充值弹窗 -->
    <el-dialog
      class="cardDialog"
      :visible.sync="chargeDia"
      :show-close="false"
      width="455px"
      top="30vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="addTitle">
        <span>充值金额</span>
      </div>
      <div class="tip">
        {{
          rechargeType == 1
            ? "手续费余额用于商户在产生交易时需支付给各渠道的费用"
            : "企业服务余额用于鉴权划扣、超量账单支付、服务升级补差。"
        }}
      </div>
      <el-form ref="form" :rules="rules" :model="form">
        <el-form-item prop="fmtPayAmt">
          <el-input
            title=""
            @keydown.native="inputKeyDown"
            placeholder="请输入充值金额"
            v-model="form.fmtPayAmt"
            type="number"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cencelReset">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </div>
    </el-dialog>
    <!-- 鉴权购买 -->
    <el-dialog
      class="cardDialog"
      :visible.sync="chargeDia1"
      :show-close="false"
      width="520px"
      top="20vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="addTitle">
        <span>鉴权购买</span>
      </div>
      <div class="tip">
        鉴权支持身份实名认证接口费用<br />
        计费说明：<br />
        自定义购买：{{ authCountInfo.customPriceTxt }}<br />
        购买套餐包：{{ authCountInfo.mealPrice }}
      </div>
      <el-form ref="form1" :rules="rules" :model="form1">
        <el-form-item label="购买方式">
          <el-radio-group v-model="form1.buyType" @input="resetCount">
            <el-radio :label="1">套餐包</el-radio>
            <el-radio :label="0">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="购买次数"
          v-if="form1.buyType == '1'"
          prop="buyCount"
        >
          <el-select
            v-model="form1.buyCount"
            placeholder="请选择"
            style="width: 100%"
            @change="seleCount"
          >
            <el-option
              v-for="(val, idx) of authMeals"
              :key="idx"
              :label="val.name"
              :value="val.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="购买次数" prop="buyCount">
          <el-input
            title=""
            placeholder="请输入购买次数"
            v-model="form1.buyCount"
            type="number"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div
          style="
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div>
            应付金额：<span style="color: #03bfc6">{{
              calcCount(form1.buyType)
            }}</span
            >元
          </div>
          <div>
            <el-button @click="cencelReset2">取消</el-button>
            <el-button type="primary" @click="handleSubmit1">确认</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 设置密码弹窗 -->
    <el-dialog
      class="cardDialog"
      :visible.sync="passwordDia"
      :show-close="false"
      width="520px"
      top="30vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="addTitle">
        <span>设置服务余额支付密码</span>
      </div>
      <div class="tip">
        服务余额可用于鉴权划扣、超量费用支付、升级套餐补差价，此处密码只适用于超量费用支付、升级套餐补差价。
      </div>
      <!-- <el-form ref="form" :rules="rules" :model="form">
        <el-form-item prop="fmtPayAmt">
        </el-form-item>
      </el-form> -->
      <div style="display: flex; flex-direction: column">
        <div class="input-box" style="margin: auto">
          <!-- 输入密码 -->
          <div style="font-size: 14px; margin-bottom: 10px">密码</div>
          <div class="input-content" @input="inputEvent">
            <input
              max="9"
              min="0"
              maxlength="1"
              data-index="0"
              v-model.number="input[0]"
              type="password"
              ref="firstinput"
              :disabled="disabledInput[0]"
            />
            <input
              max="9"
              min="0"
              maxlength="1"
              data-index="1"
              v-model.number="input[1]"
              type="password"
              :disabled="disabledInput[1]"
            />
            <input
              max="9"
              min="0"
              maxlength="1"
              data-index="2"
              v-model.number="input[2]"
              type="password"
              :disabled="disabledInput[2]"
            />
            <input
              max="9"
              min="0"
              maxlength="1"
              data-index="3"
              v-model.number="input[3]"
              type="password"
              :disabled="disabledInput[3]"
            />
            <input
              max="9"
              min="0"
              maxlength="1"
              data-index="4"
              v-model.number="input[4]"
              type="password"
              :disabled="disabledInput[4]"
            />
            <input
              max="9"
              min="0"
              maxlength="1"
              data-index="5"
              v-model.number="input[5]"
              type="password"
              :disabled="disabledInput[5]"
            />
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cencelReset1">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { isAmount } from "@/utils/validate";

export default {
  name: "accountView",
  data() {
    return {
      curSeleObj: null,
      authCountInfo: {},
      authMeals: [],
      // 输入数组
      input: ["", "", "", "", "", ""],
      // 输入框是否禁用
      disabledInput: [false, false, false, false, false, false],
      host: window.location.origin,
      form: {
        fmtPayAmt: "",
      },
      form1: {
        buyType: 1,
        buyCount: "",
      },
      sortList: [],
      rules: {
        fmtPayAmt: [
          { required: true, message: "金额不能为空", trigger: "change" },
          {
            validator: this.checkAmount,
            trigger: "change",
          },
        ],
        buyCount: [
          { required: true, message: "购买次数不能为空", trigger: "change" },
          {
            validator: this.buyCount,
            trigger: "change",
          },
        ],
      },
      list: [],
      rechargeType: 1, //默认手续费类型
      chargeDia: false,
      chargeDia1: false,
      passwordDia: false,
      authInfo: {},
      authAmount: "0.00", //鉴权余额
      authCount: 0, //鉴权次数
    };
  },
  created() {
    //console.log(window.location.origin)
    this.$http.get("/sys/meal/listMeal").then((res) => {
      if (res.code === "0000") {
        console.log(res.data);
        this.list = res.data;
      }
    });
    //获取鉴权信息
    this.getAuthInfo();
  },
  methods: {
    toEditRegis() {
      this.$router.push({
        path: "/editCompanyPersonInfo",
        query: { command: 1 },
      });
    },
    createAuthAcc() {
      this.$http
        .post("/api/merchant/memberauth/insertAuthAccountInfo")
        .then((res) => {
          if (res.code === "0000") {
            this.$message.success("申请开通成功！");
          }
          this.getAuthInfo();
        });
    },
    seleCount(value) {
      let seleObj = this.authMeals.find((item) => item.value == value);
      console.log(seleObj);
      this.curSeleObj = seleObj;
    },
    calcCount(type) {
      // console.log(type)
      if (type == "1") {
        if (this.form1.buyCount) {
          return (
            (this.curSeleObj?.unitPrice * this.curSeleObj?.value) / 100 || 0
          );
        } else {
          return 0;
        }
      } else {
        // console.log(this.authCountInfo.customPrice)
        // console.log(this.form1.buyCount)
        return (
          (this.authCountInfo.customPrice * this.form1.buyCount) / 100 || 0
        );
      }
    },
    resetCount() {
      this.form1.buyCount = "";
    },
    inputEvent(e) {
      var index = e.target.dataset.index * 1;
      var el = e.target;
      // 限制只能输入数字
      el.value = el.value.replace(/[^\d]/g, "");
      if (el.value.length >= 1) {
        // 密文显示、不可编辑、不可回退、即时显示
        this.disabledInput[index] = true;
        if (el.nextElementSibling) {
          el.nextElementSibling.focus();
        }
      }
    },
    getAuthInfo() {
      this.$http
        .get("/api/merchant/memberauth/getAuthAccount?business=balance")
        .then((res) => {
          if (res.code === "0000") {
            console.log(res.data);
            this.authInfo = res.data;
            this.authAmount = (res.data && res.data.fmtAuthBalance) || "0.00";
            this.authCount = (res.data && res.data.authCount) || 0;
          }
        });
    },
    inputKeyDown(event) {
      const { key } = event;
      const filterValue = ["e", "+", "-", "Enter"];
      console.log(key);
      if (filterValue.includes(key)) {
        event.returnValue = false;
        return false;
      }
      return true;
    },
    checkAmount(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入充值金额"));
      } else if (!isAmount(value)) {
        callback(new Error("金额必须为整数或者保留两位小数"));
      } else if (Number(value) > 99999999.99) {
        callback(new Error("超出最大输入限制"));
      } else if (value <= 0) {
        callback(new Error("金额必须大于0"));
      } else {
        callback();
      }
    },
    buyCount(rule, value, callback) {
      if (!/^([0-9]$)|(^[0-9]{1,8}$)$/.test(+value)) {
        callback(new Error("请输入10~100000之间的整数"));
      } else if (+value >= 10 && +value <= 100000) {
        callback();
      } else {
        callback(new Error("请输入10~100000之间的整数"));
      }
    },
    pathTo() {
      this.$router.push(`/qiye/balanceDetails`);
      // this.$router.push({
      //   name: "balanceDetails",
      //   query: { type },
      // });
    },
    toPurchase(idx, id, mealId, type) {
      if (idx != 0) {
        //非融聚
        if (!this.list[0].isBuy || this.list[0].isExpire) {
          this.$message.warning(`请先购买 ${this.list[0].serviceName}`);
          return;
        }
      }
      this.$router.push({
        name: "purchaseView",
        query: { id, type: idx, mealId, command: type },
      });
    },
    openDia(type) {
      this.rechargeType = type;
      this.chargeDia = true;
    },
    openDia2() {
      this.$http.get("api/merchant/memberauth/getAuthMeal").then((res) => {
        if (res.code === "0000") {
          console.log(res.data);
          this.authCountInfo = res.data;
          this.authMeals = this.authCountInfo.authMeals;
          this.chargeDia1 = true;
        }
      });
    },
    openDia1() {
      this.passwordDia = true;
      this.$nextTick(() => {
        console.log(this.$refs.firstinput);
        let firstinput = this.$refs.firstinput;
        firstinput.focus();
      });
    },
    cencelReset() {
      this.chargeDia = false;
      this.$refs.form.resetFields(); //重置状态
    },
    cencelReset2() {
      this.chargeDia1 = false;
      this.$refs.form1.resetFields(); //重置状态
    },
    cencelReset1() {
      this.passwordDia = false;
      this.input = ["", "", "", "", "", ""];
      this.disabledInput = [false, false, false, false, false, false];
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let param = {
            ...this.form,
          };
          // console.log(param);
          this.$http
            .post("/api/merchant/memberauth/recharge", param)
            .then((res) => {
              if (res.code === "0000") {
                this.cencelReset();
                window.open(res.data.cashierUrl);
                setTimeout(() => {
                  this.$router.push("/qiye/orderCenter");
                }, 3000);
                // this.$message.success("充值成功！");
                // this.getAuthInfo();
              }
            });
        } else {
          return false;
        }
      });
    },
    handleSubmit1() {
      this.$refs.form1.validate((valid) => {
        if (valid) {
          let param = {
            type: this.form1.buyType,
            authCount: parseInt(this.form1.buyCount),
            unitPrice:
              this.form1.buyType == "1"
                ? this.curSeleObj.unitPrice
                : this.authCountInfo.customPrice,
          };
          console.log(param);
          this.$http
            .post("/api/merchant/memberauth/purchaseAuth", param)
            .then((res) => {
              if (res.code === "0000") {
                this.$message.success("购买鉴权次数成功");
                this.cencelReset2();
                this.getAuthInfo();
              }
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.input-box {
  .input-content {
    width: 441px;
    height: 64px;
    padding: 12px 0;
    border: 1px solid #e5e5e5;
    border-radius: 2px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    input {
      color: inherit;
      font-family: inherit;
      border: 0;
      outline: 0;
      // border-bottom: 1px solid #919191;
      height: 40px;
      width: 72px;
      border-right: 1px solid #e5e5e5;
      font-size: 44px;
      text-align: center;
    }
    input:nth-of-type(6) {
      border: none;
    }
  }

  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    appearance: none;
    margin: 0;
  }
}

.mainTitle {
  margin-bottom: 20px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #869daa;
}

.wrap {
  margin-bottom: 10px;
  :deep(.el-card) {
    position: relative;
  }
  .statusTip {
    position: absolute;
    top: -3px;
    right: 20px;

    width: 93px;
    height: 25px;
    background: #25b5d9;
    border-radius: 0px 0px 6px 6px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    text-align: center;
    line-height: 25px;
  }
  .item {
    text-align: center;
    min-height: 253px;
    padding-top: 22px;
    padding-bottom: 25px;
    color: #03bfc6;
    .img {
      width: 72px;
      height: 72px;
    }
    .type {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #4f595f;
      .meal {
        height: 20px;
        line-height: 20px;
        background: #869daa;
        border-radius: 2px;
        padding: 0 12px;
        font-size: 12px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #ffffff;
        margin-left: 10px;
      }
      margin-top: 24px;
      //   margin-bottom: 10px;
    }
    .date {
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #bfbfbf;
      margin-top: 10px;

      width: 100%;
      min-height: 16px;
    }

    .tag {
      width: 90px;

      border-radius: 4px;
      font-weight: 500;
      color: #ffffff;
      line-height: 30px;
      height: 30px;
      margin: 0 auto 40px;
    }
    .showTag {
      background: #869daa;
    }

    .btn {
      margin-top: 24px;
      width: 156px;
      height: 32px;
      border-radius: 16px;

      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #ffffff;
      //   line-height: 20px;
    }
    .overdue {
      color: #e23d28;
    }
  }
}
.wrap2 {
  display: flex;
  justify-content: space-between;

  .item2 {
    display: flex;
    justify-content: space-between;
    flex: 1;
    align-items: center;
    padding: 0 8px;
    color: #666;
    .number {
      font-weight: bold;
      margin-left: 18px;
    }
    .primary {
      color: #03bfc6;
      margin-left: 18px;
    }
    .warn {
      color: #f69c1f;
      margin-left: 18px;
    }
    .error {
      color: #e23d28;
      margin-left: 18px;
    }

    .look {
      margin-left: 20px;
    }

    .tip {
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
    }
  }

  .one {
    padding-right: 40px;
    border-right: 1px solid #bfbfbf;
  }
  .two {
    padding-right: 20px;
    padding-left: 28px;
  }
}

.content {
  .cardDialog {
    .addTitle {
      font-size: 20px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: bold;
      color: rgba(0, 0, 0, 0.85);
    }
    .tip {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      margin-top: 12px;
      margin-bottom: 30px;
      span {
        color: #03bfc6;
      }
    }
    :deep(.el-dialog) {
      border-radius: 16px;
    }
    :deep(.el-dialog__body) {
      padding: 10px 40px;
      padding-bottom: 60px;
    }
    :deep(.el-button--small) {
      width: 74px;
    }
    :deep(.el-input__inner) {
      padding-left: 12px;
    }
    :deep(.el-form-item__content) {
      position: relative;
    }
    .form-img {
      width: 22px;
      border-radius: 22px;
      position: absolute;
      top: 5px;
      left: 10px;
      z-index: 1;
    }
  }
}

.btn-small {
  width: 96px !important;
}

:deep(.el-input__inner) {
  line-height: 1px !important;
}
:deep(
    input[type="number"]::-webkit-inner-spin-button,
    input[type="number"]::-webkit-outer-spin-button
  ) {
  -webkit-appearance: none;
  margin: 0;
}
</style>
